<template>
  <div class="bgc-default pad-20">
    <div class="bg-color-white pad-20">
      <div style="margin-bottom: 15px;">
        <el-button type="primary" @click="exportOrder">导出配送单</el-button>
        <el-button v-if="isExportSuccess" type="text" @click="jumpToReportCenter">跳转报表中心</el-button>
      </div>
      <!--顶部搜索 -->
      <div class="top-operate-default flex-col" style="align-items: baseline; padding: 20px 0; height: 100%; ">
        <div class="search-item">
          <el-form :model="queryParams" ref="queryForm" :inline="true" label-width="100px" class="search-item">
            <el-form-item label="搜索订单：" style="margin-bottom:0px">
              <el-select v-model="queryParams.textCol">
                <el-option label="配送单号" value="deliveryNo"></el-option>
                <el-option label="团长昵称" value="memberNickname"></el-option>
                <el-option label="团长姓名" value="memberRealName"></el-option>
                <el-option label="团长手机号" value="memberPhone"></el-option>
                <el-option label="商品名称" value="goodsTitle"></el-option>
                <el-option label="配送地址" value="deliveryAddress"></el-option>
              </el-select>
              <el-input v-model="queryParams.textValue" placeholder="请输入内容" style="width: 200px">
              </el-input>
            </el-form-item>
            <el-form-item label="订单来源活动：" style="margin-bottom:0px">
              <el-select v-model="queryParams.promotionId" class="orderSourceActivity" filterable placeholder="输入活动名称"
                style="width: 200px" clearable>
                <el-option style="width: 200px" v-for="item in orderSourceActivityOptions" :key="item.promotionId"
                  :label="item.title" :value="item.promotionId">
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="时间筛选：" style="margin-bottom:0px">
              <el-select class="pad-l-10" v-model="dateColumn">
                <el-option v-for="item in searchDeliveryTimeTypeList" :key="item.value" :label="item.label"
                  :value="item.value"> </el-option>
              </el-select>
              <el-date-picker v-model="dateRange" type="datetimerange" range-separator="至"
                value-format="yyyy-MM-dd HH:mm:ss" :default-time="['00:00:00', '23:59:59']" start-placeholder="开始日期"
                end-placeholder="结束日期">
              </el-date-picker>
            </el-form-item>
          </el-form>
          <el-button-group class="mar-l-20">
            <el-button type="primary" @click="doSearch">查询</el-button>
            <el-button @click="doResetSearch">重置</el-button>
          </el-button-group>
        </div>
      </div>
      <div class="tabs-box mar-t-15">
        <!--订单状态 -2: 已付款取消 -1: 未付款取消 0: 未付款, 1: 已付款 2: 已发货 3: 已收货 4: 已完成 -->
        <!--待配货对应已付款，待提货对应已发货，已提货对应已收货 -->
        <el-tabs type="card" v-model="deliveryStatus" @tab-click="doChangeTab">
          <el-tab-pane v-for="item in deliveryStatusLabels" :key="item.name" :label="item.title" :name="item.name">
          </el-tab-pane>
        </el-tabs>
      </div>
      <!-- 全选、操作 目前只有批量发货需要批量操作 -->
      <div class="pad-t-15 pad-b-15 font-14 v-align-c" v-if="deliveryStatus === '10'">
        <el-checkbox class="mar-l-14 mar-r-0" v-model="allChecked" @change="selectAll"><span
            class="mar-l-20">当页全选</span></el-checkbox>
        <span class="pad-l-4 pad-r-4">|</span>
        <div class="width-80">已选{{multipleSelection.length}}项</div>
        <el-button @click="batchDelivery">批量发货</el-button>
      </div>
      <el-table ref="multipleTable" :data="dataList" @selection-change="handleSelectionChange" v-loading="listLoading"
        element-loading-text="加载中">
        <el-table-column width="50px" type="selection"></el-table-column>
        <!--        <el-table-column width="200px" label="活动名称" prop="promotionTitle">
          <template slot-scope="scope">
            <div v-if="scope.row.promotionList != null && scope.row.promotionList.length > 0">
              <span v-for="item in scope.row.promotionList">{{item.promotionTitle}}</span><br />
            </div>
          </template>
        </el-table-column> -->
        <el-table-column width="200px" label="配送单号" prop="deliveryNo"></el-table-column>
        <el-table-column width="300px" label="团长/门店信息" prop="orderNo">
          <template slot-scope="scope">
            <div @click="handleUpdate(scope.row)" class="flex v-align-c cursor-p">
              <div class="vip-icon-box"><img v-if="scope.row.memberFlag == 1" :src="vipIcon" alt=""></div>
              <label><img :src="scope.row.memberAvatar" class="user-avatar cursor-p"
                  v-if="scope.row.memberAvatar"></label>
              <div class="font-14 pad-l-10">
                <div><span class="font-color-9" v-if="scope.row.memberNickname">昵称：</span>{{scope.row.memberNickname}}
                </div>
                <div><span class="font-color-9" v-if="scope.row.memberPhone">手机：</span>{{scope.row.memberPhone}}</div>
              </div>
            </div>
          </template>
        </el-table-column>
        <el-table-column min-width="240px" label="配送地址" prop="deliveryAddress">
          <template slot-scope="scope">
            <div class="flex v-align-c cursor-p">
              <label>
                <el-image v-if="scope.row.memberTakeStoreImage" alt="点击查看大图" class="user-avatar cursor-p"
                  :src="scope.row.memberTakeStoreImage" :preview-src-list="[scope.row.memberTakeStoreImage]"></el-image>
              </label>
              <div class="font-12 pad-l-10 font-w">
                <div>{{scope.row.deliveryAddress}}
                </div>
                <div><span style="color: red;">{{scope.row.memberTakeStoreType}}</span>
                </div>
                <div>{{scope.row.memberTakeStoreName}}
                </div>
              </div>
            </div>
          </template>
        </el-table-column>
        <el-table-column width="120px" label="商品数量" prop="goodsNum" />
        <el-table-column width="200px" label="生成时间" prop="createTime" />
        <el-table-column width="200px" label="配送时间" prop="deliveryTime" />
        <el-table-column width="200px" label="签收时间" prop="receiveTime" />
        <el-table-column width="150px" label="状态">
          <template slot-scope="scope">
            <template>
              <b>{{ dict.deliveryStatus[scope.row.deliveryStatus]}}</b>
            </template>
          </template>
        </el-table-column>
        <el-table-column min-width="240px" label="操作" align="right" fixed="right">
          <template slot-scope="scope">
            <el-button type="text" size="medium" @click="showDetail(scope.row)">查看详情</el-button>
            <!-- <el-button type="text" size="medium" @click="exportDelivery(scope.row)">导出</el-button> -->
            <el-popover placement="bottom" width="100" trigger="hover" popper-class="popover-class">
              <el-button class="mar-l-10" type="text" size="medium" slot="reference">导出
              </el-button>
              <el-button type="text" size="medium" @click="exportDelivery(scope.row, 1)">仓库备货单</el-button>
              <el-button type="text" size="medium" @click="exportDelivery(scope.row, 2)">司机配送单</el-button>
              <el-button type="text" size="medium" @click="exportDelivery(scope.row, 3)">商品配送表</el-button>
            </el-popover>
          </template>
        </el-table-column>
      </el-table>
      <pagination v-show="total>0" :total="total" :page.sync="queryParams.currentPage" :limit.sync="queryParams.size"
        @pagination="getList" />
    </div>
    <!-- 选品库dialog -->
    <el-dialog :visible.sync="selectionExportVisible" title="导出配送单" width="30%" :center="true">
      <el-header>
        <div>
          <label>操作：</label>
          <el-radio v-model="selecExportConditionForm.exportType" label="1" name="1">仓库备货单</el-radio>
          <el-radio v-model="selecExportConditionForm.exportType" label="2" name="2">司机配送单</el-radio>
          <el-radio v-model="selecExportConditionForm.exportType" label="3" name="3">商品配送单</el-radio>
        </div>
        <div class="mar-t-15">
          <span>按生成时间导出数据：</span>
          <el-date-picker v-model="generateGroupBuyDateRange" type="datetimerange" range-separator="至"
          	value-format="yyyy-MM-dd HH:mm:ss" :default-time="['00:00:00', '23:59:59']"
          	start-placeholder="开始日期" end-placeholder="结束日期">
          </el-date-picker>
        </div>
      </el-header>
      <div slot="footer" class="dialog-footer">
        <el-button @click="closeselectionExportDialog">取消</el-button>
        <el-button type="primary" @click="doSaveSelectionExportType">确认</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
  import {
    getPromotionForSelControlList
  } from '@/api/sell/promotion'
  import {
    pageDelivery,
    statDelivery,
    batchExportCommanderDelivery,
    batchDelivery
  } from '@/api/goods/delivery'
  import {
    downloadFile,
    jumpToReportCenter
  } from '@/api/common/common'
  export default {
    data() {
      return {
        deliveryStatus: '10',
        memberId: '',
        // 文本model
        textCol: 'orderNo',
        textValue: '',
        allChecked: false,
        // 选择订单id
        selectOrderId: '',
        // 选中订单id集合
        selectOrderIds: [],
        dateColumn: 'createTime',
        dateRange: [],
        dataList: [],
        total: 0,
        multipleSelection: [],
        listLoading: true,
        orderTimeColName: '',
        queryParams: {
          currentPage: 1,
          size: 10,
          dateColumn: 'createTime',
          textCol: 'deliveryNo'
        },
        // 订单时间搜索类型
        searchDeliveryTimeTypeList: [{
          value: 'createTime',
          label: '生成时间'
        }, {
          value: 'deliveryTime',
          label: '配送时间'
        }, {
          value: 'receiveTime',
          label: '签收时间'
        }],
        orderSourceActivityOptions: [],
        deliveryStatusLabels: [{
          name: '10',
          title: '待配送(0)'
        }, {
          name: '20',
          title: '待签收(0)'
        }, {
          name: '30',
          title: '已签收(0)'
        }, {
          name: '-1',
          title: '全部(0)'
        }],
        selectionExportVisible: false,
        isExportSuccess: false,
        generateGroupBuyDateRange: [],
        // 批量导出条件
        selecExportConditionForm: {
          enterpriseId: this.getEnterpriseId(),
          exportType: '1', // 导出类型0-仓库配送单；1-司机配送单；2-商品配送单
          generateTime: '',
          payStartTime: '',
          payEndTime: ''
        }
      }
    },
    computed: {},
    created() {
      const queryParams = this.getCurrentPage().query
      if (queryParams.memberId) {
        this.memberId = queryParams.memberId
      }
      if (queryParams.promotionId) {
        this.queryParams.promotionId = queryParams.promotionId
      }

      this.getList()
      this.getPromotionForSelControlList()
    },
    methods: {
      doCount() {
        this.count = this.count + 1
      },
      doSearch() {
        this.queryParams.currentPage = 1
        this.getList()
      },
      doResetSearch() {
        const originData = this.$options.data()
        this.dateRange = []
        this.dateColumn = originData.dateColumn
        if (this.$refs['queryForm']) {
          this.$refs['queryForm'].resetFields()
        }
        this.queryParams = originData.queryParams
        this.doSearch()
      },
      doChangeTab(val) {
        this.doSearch()
      },
      selectAll() {
        if (this.multipleSelection.length === 0 || this.multipleSelection.length < this.dataList.length) {
          this.dataList.forEach(item => {
            this.$refs.multipleTable.toggleRowSelection(item, true)
          })
        } else {
          this.$refs.multipleTable.clearSelection()
        }
      },
      // 勾选事件
      handleSelectionChange(val) {
        this.multipleSelection = val
        if (this.multipleSelection.length === this.dataList.length) {
          this.allChecked = true
        } else {
          this.allChecked = false
        }
      },
      // 设置查询条件
      setQueryParams() {
        this.queryParams.deliveryStatus = this.deliveryStatus === '-1' ? '' : this.deliveryStatus
        this.queryParams.enterpriseId = this.getEnterpriseId()
        this.queryParams[this.queryParams.textCol] = this.queryParams.textValue
        this.queryParams.startDate = (this.dateRange && this.dateRange.length > 0) ? this.dateRange[0] : ''
        this.queryParams.endDate = (this.dateRange && this.dateRange.length > 1) ? this.dateRange[1] : ''
        this.queryParams.dateColumn = this.dateColumn
      },
      getList() {
        this.listLoading = true
        this.statDelivery()
        this.setQueryParams()
        pageDelivery(this.queryParams).then(response => {
          this.listLoading = false
          if (response.isError) return
          this.total = response.data.total
          this.dataList = response.data.records
          this.dict = response.data.dict
        })
      },
      // 统计配送单
      statDelivery() {
        const that = this
        statDelivery({
          enterpriseId: that.getEnterpriseId(),
          promotionId: this.queryParams.promotionId
        }).then(response => {
          if (response.isError) return
          for (let i = 0; i < that.deliveryStatusLabels.length; i++) {
            let title = that.deliveryStatusLabels[i].title
            title = title.substring(0, title.indexOf('('))
            that.deliveryStatusLabels[i].title = title + '(' + response.data[title] + ')'
          }
        })
      },
      getPromotionForSelControlList() {
        const that = this
        const params = {}
        params.userType = 1
        params.userId = this.getEnterpriseId()
        params.activityType = 2
        getPromotionForSelControlList(params).then(response => {
          if (response.isError) return
          that.orderSourceActivityOptions = response.data
        })
      },
      showDetail(row) {
        this.$router.push({
          path: '/community/order/delivery/detail/index',
          query: row
        })
      },
      exportDelivery(row, type) {
        var deliveryType = '仓库备货单.xlsx'
        if (type === 2) {
          deliveryType = '司机配送单.xlsx'
        } else if (type === 3) {
          deliveryType = '商品配送表.xlsx'
        }
        downloadFile('/goods/delivery/exportDeliveryData', {
          exportType: type,
          deliveryId: row.deliveryId
        }, deliveryType)
      },
      exportOrder() {
        this.selectionExportVisible = true
      },
      doSaveSelectionExportType() {
        const that = this
        that.selecExportConditionForm.payStartTime = that.generateGroupBuyDateRange[0]
        that.selecExportConditionForm.payEndTime = that.generateGroupBuyDateRange[1]
        if (that.selecExportConditionForm.payStartTime === '' || that.selecExportConditionForm.payEndTime === '') {
          this.msgError('请正确选择时间')
          return
        }
        that.selectionExportVisible = false
        batchExportCommanderDelivery(this.selecExportConditionForm).then(response => {
          if (response.isError) return
          that.isExportSuccess = true
          that.msgSuccess('批量导出成功,请前往报表中心下载')
        })
      },
      jumpToReportCenter() {
        jumpToReportCenter(this, undefined, true)
      },
      // 关闭批量导出dialog
      closeselectionExportDialog() {
        this.selectionExportVisible = false
      },
      batchDelivery() {
        const selections = this.multipleSelection
        if (selections.length === 0) {
          this.msgError('请先选择要操作的数据')
          return
        }
        this.$confirm('确定发货？', '操作确认', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          const deliveryIds = []
          selections.forEach(e => {
            deliveryIds.push(e.deliveryId)
          })
          const data = {}
          data.deliveryIds = deliveryIds
          this.listLoading = true
          batchDelivery(data).then(response => {
            this.listLoading = false
            if (response.isError) return
            this.msgSuccess(response.msg)
            this.getList()
          })
        })
      }
    }
  }
</script>

<style>
  .orderSourceActivity {
    width: 200px !important;
  }

  .orderSourceActivity .el-input {
    width: 200px !important;
  }
</style>
<style lang="less" scoped>
  .user-avatar {
    width: 65px;
    height: 65px;
    display: block;
    padding: 1px;
    border: #efefef 1px solid;
  }

  .goods-title {
    color: #155bd4;
    line-height: 1.2;
  }

  .title-row {
    margin-top: 44px;
    margin-bottom: 25px;
  }

  // 2行文字展示
  .line-2 {
    line-height: 1.4;
    overflow: hidden;
    text-overflow: ellipsis;
    display: -webkit-box;
    -webkit-line-clamp: 2;
    -webkit-box-orient: vertical;
    word-break: break-word;
  }
</style>
